/*
 * Copyright © 2018 iFund. All rights reserved.
 */
package com.climber.android.commonres.widget;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
import android.widget.TextView;

import io.library.android.indicator.Indicator;
import io.library.android.indicator.slidebar.ScrollBar;

/**
 * tab的文本多宽scrollbar就显示多宽，左上角和右上角圆角，左下角和右下角直角
 */
public class RoundTextWidthColorBar implements ScrollBar {
    protected Gravity gravity;
    protected View view;
    protected int height;
    protected int width;

    protected Indicator indicator;
    protected int realWidth = 0;

    public RoundTextWidthColorBar(Context context,int drawableResId, Indicator indicator, int height) {
        this.view = new View(context);
        this.view.setBackgroundResource(drawableResId);
        this.height = height;
        this.gravity = Gravity.BOTTOM;

        this.indicator = indicator;
    }

    @Override
    public int getHeight(int tabHeight) {
        if (height == 0) {
            return tabHeight;
        }
        return height;
    }

    @Override
    public View getSlideView() {
        return view;
    }

    @Override
    public Gravity getGravity() {
        return gravity;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        int width1 = getTextWidth(getTextView(position));
        int width2 = getTextWidth(getTextView(position + 1));
        realWidth = (int) (width1 * (1 - positionOffset) + width2 * (positionOffset));
    }

    @Override
    public int getWidth(int tabWidth) {
        if (realWidth == 0) {
            if (indicator.getIndicatorAdapter() != null) {
                TextView textView = getTextView(indicator.getCurrentItem());
                if (textView != null) {
                    realWidth = getTextWidth(textView);
                }
            }
        }
        return realWidth / 3;
    }

    /**
     * 如果tab不是textView，可以通过重写该方法，返回tab里面的textView。
     *
     * @param position
     * @return
     */
    protected TextView getTextView(int position) {
        return (TextView) indicator.getItemView(position);
    }

    private int getTextWidth(TextView textView) {
        if(textView==null){
            return 0;
        }
        Rect bounds = new Rect();
        String text = textView.getText().toString();
        Paint paint = textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.left + bounds.width();
        return width;
    }

}